<template>
  <div
      :style="{
      width: $store.getters.isMobile ? '1200px' : undefined,
      height: '100%',
      overflow: 'hidden',
    }"
  >
    <div v-if="table.length" style="padding: 10px;width: 100%; height: 100%;">
      <a-tabs v-model:activeKey="activeKey" type="card" @change="Tabchange">
        <a-tab-pane
            :key="tab.id"
            :tab="tab.name"
            v-for="tab in table"
            style="background-color: #ffff; padding: 20px;"
        >
          <a-spin :spinning="tabSpinning">
            <section  id="countDataRef">
              <a-row
                  type="flex"
                  justify="space-between"
                  style="padding-bottom: 20px"
              >
                <a-col class="flex align-center" style="margin-bottom: 10px">
                  <div
                      @click="handleStatusFilter(item)"
                      v-for="(item, index) of statusList"
                      :key="index"
                      class="top-tag"
                      :class="
                    currentStatus == item.title && !showTwoDimensional
                      ? 'top-tag-active'
                      : ''
                  "
                  >
                    <span class="icon" :style="{ background: item.color }"></span>
                    <span class="ml-2">{{ item.title }}</span>
                  </div>
                </a-col>
                <a-col>
                  <a-space>
                    <a-button
                        v-if="view3dData.layerId"
                        type="primary"
                        @click="to3DView"
                    >3D可视化</a-button
                    >
                    <a-button
                        type="primary"
                        @click="to2DView"
                        :loading="showTwoDimensLoading"
                    >{{
                        showTwoDimensional ? "取消展示2D平面图" : "展示2D平面图"
                      }}</a-button
                    >
                    <a-input-search
                        v-if="!showTwoDimensional"
                        v-model:value="searchValue"
                        placeholder="房间号搜索"
                        style="width: 150px"
                        @search="onSearch"
                        allowClear
                    />

                    <a-button type="primary" @click="btnAdd"
                    >新建{{ $L("房源") }}</a-button
                    >
                  </a-space>
                </a-col>
              </a-row>
            </section>
            <section class="section-box hide-scroller-bar"
                     :style="{ height:`calc(100% - ${offsetSectionHeight }px)` }" >
              <a-row
                  style="margin: -10px 0 15px 0"
                  v-if="currentStatus != '' && !showTwoDimensional"
              >
                <a-switch
                    checked-children="显示无关房源"
                    un-checked-children="隐藏无关房源"
                    v-model:checked="checkedMode"
                />
              </a-row>
              <a-row v-if="tab.buildLevelList.length" type="flex" style="width: 100%;height: 100%; flex: 1">
                <a-col class="section-left hide-scroller-bar">
                  <a-menu
                      v-model:selectedKeys="activeBuildId"
                      v-model:openKeys="openedMenu"
                      mode="inline"
                      class="build_level_menu hide-scroller-bar"
                      @select="buildMenuSelect"
                  >
                    <template v-for="item of tab.buildLevelList" :key="item.id">
                      <template v-if="!item.children">
                        <a-menu-item :key="item.id">
                          <a-tooltip>
                            <template #title>{{ item.title }}</template>
                            <div class="textEllipsis">
                              {{ item.title }}
                            </div>
                          </a-tooltip>
                        </a-menu-item>
                      </template>
                      <template v-else>
                        <sub-menu :menu-info="item" :key="item.id" />
                      </template>
                    </template>
                  </a-menu>
                </a-col>
                <a-col class="section-right hide-scroller-bar">
                  <template v-if="!showTwoDimensional">
                    <a-row
                        v-for="layer in profilesList.list"
                        :key="layer.id"
                        style="margin-bottom: 5px"
                        type="flex"
                        :style="getListStyle(layer.room_list)"
                        :wrap="false"
                    >
                      <a-col flex="80px" style="padding: 5px 0" >
                        <div class="room-left">
                          <div class="layer-name">{{ layer.layer_name }}</div>
                          <div class="build-area">{{ layer.build_area }}㎡</div>
                        </div>
                      </a-col>
                      <a-col flex="auto">
                        <div class="room-right">
                          <div
                              class="room-box"
                              v-for="room of layer.room_list"
                              :key="room.id"
                              :style="room.is_rent ? 'width:200px' : 'width:200px'"
                              :class="{
                            viewHide:viewMode==2&&
                            currentStatus &&
                            currentStatus.key != room.roomColorType,
                          }"
                          >
                            <a-tooltip>
                              <template #title>
                                <div >
                                  <div>
                                <span style="min-width: 100px;display: inline-block;">
                                  {{ room.room_name }}
                                      <span v-if=" room.rent_area && (room.room_status == 20 || room.room_status == 30) " >
                                        ({{ room.rent_area.lease_square }}m²/{{ room.build_area }}m²)
                                      </span >
                                      <span v-else-if="room.is_lock" >
                                        ({{ room.locked_area }}m²/{{ room.build_area }}m²)
                                      </span>
                                      <span v-else>({{ room.build_area }}m²)</span>
                                </span>
                                    <span style="min-width: 100px;display: inline-block;"> {{ room.tenant_name ? room.tenant_name : '未入住' }}</span>
                                  </div>
                                  <div>
                                    <span style="min-width: 100px;display: inline-block;">人数：{{room.peopleNum}}</span>
                                    <span style="min-width: 100px;display: inline-block;">用途：{{room.house_type_txt ? room.house_type_txt : '--'}}</span>
                                  </div>
                                  <div v-if="room.over_fee">{{room.over_fee}}元</div>
                                </div>
                              </template>
                              <div
                                  class="room"
                                  :style="'background:' + room.roomColor"
                                  :class="{
                              bordered: room.show_status != 4,
                              dark:
                                viewMode==1&&
                                currentStatus &&
                                currentStatus.key != room.roomColorType,

                            }"
                                  @click="onRoomClick(room, layer)"
                              >
                                <div class="textEllipsis" style="font-size: 13px">
                              <span style="width: 60%;display: inline-block;" class="textEllipsis">
                                {{ room.room_name }}
                                <span v-if=" room.rent_area && (room.room_status == 20 || room.room_status == 30) " >
                                        ({{ room.rent_area.lease_square }}m²/{{ room.build_area }}m²)
                                      </span >
                                <span v-else-if="room.is_lock" >
                                        ({{ room.locked_area }}m²/{{ room.build_area }}m²)
                                      </span>
                                <span v-else>({{ room.build_area }}m²)</span>
                              </span>
                                  <span style="width: 40%;display: inline-block;" class="textEllipsis">{{ room.tenant_name ? room.tenant_name : '未入住' }}</span>
                                </div>
                                <div class="textEllipsis" style="font-size: 13px">
                                  <span style="width: 60%;display: inline-block;" class="textEllipsis">人数：{{room.peopleNum}}</span>
                                  <span style="width: 40%;display: inline-block;" class="textEllipsis">用途：{{room.house_type_txt ? room.house_type_txt : '--'}}</span>
                                </div>
                                <div v-if="room?.over_fee ? Number(room.over_fee) : 0" class="textEllipsis" style="font-size: 13px">
                                  <span style="color: red;">
                                      欠费金额：{{room.over_fee}}元
                                  </span>
                                </div>

                                <div
                                    class="room-bottom"
                                    v-if="room.show_tags && room.show_tags.length"
                                >
                                  <div class="room-tags">
                                <span
                                    v-for="(tag, tagIndex) of room.show_tags"
                                    :key="tagIndex"
                                    :style="{
                                    backgroundColor: tag === '逾' ? 'rgba(221, 25, 25, 0.4)' : (tag === '售' ? 'rgba(0, 0, 255, 0.4)' : 'rgba(0, 0, 0, 0.2)'),
                                  }"
                                    class="tag"
                                >
                                  {{ tag }}
                                </span>
                                  </div>
                                </div>
                              </div>
                            </a-tooltip>
                          </div>
                        </div>
                      </a-col>
                    </a-row>
                  </template>
                  <!--  2D图    -->
                  <template v-else>
                    <div style="display: flex">
                      <div style="margin-right: 16px">
                        <div
                            v-for="layer in twoDimensionalLayers"
                            :key="layer.layer_id"
                            class="two_map_left"
                            :class="
                            activeTwoDimensionalLayerId == layer.layer_id
                              ? 'active_map_left'
                              : ''
                          "
                            @click.stop="change2DLayer(layer.layer_id)"
                        >
                          {{ layer.layer_name }}
                        </div>
                      </div>
                      <div
                          class="canvas-container-wrap"
                          :id="`sectionDrawingCanvas${tab.id}`"
                      >
                        <div class="canvas-container-action">
                          <a-space>
                            <a-button
                                v-if="showTwoDimensional"
                                type="primary"
                                shape="circle"
                                @click.stop="handleEditLayer"
                            >
                              <template #icon><EditOutlined /></template>
                            </a-button>
                            <a-button
                                type="primary"
                                shape="circle"
                                @click.stop="canvasFitZoom"
                            >
                              <template #icon><RedoOutlined /></template>
                            </a-button>
                          </a-space>
                        </div>
                        <canvas
                            class="canvas-sectionDrawing"
                            :class="`canvas-sectionDrawing-${tab.id}`"
                        ></canvas>
                      </div>
                    </div>
                  </template>
                </a-col>
              </a-row>
              <!-- 暂无数据 -->
              <Empty v-else />
            </section>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div v-else class="noData">
      <a-empty description="暂无楼宇" />
    </div>

    <!-- 新增房源弹窗 -->
    <AddHouse
        v-if="visible"
        :visible="visible"
        @cancel="btnCancel()"
        @success="btnCancel('success')"
    />
    <!-- 详情 -->
    <RoomDrawer
        v-if="visibleDetails"
        :visible="visibleDetails"
        @cancel="btnCancelDetails"
        :maxRoomNumber="maxRoomNumber"
        :detail="roomDetail"
        pageFrom="SpaceManagement"
    />

    <Layer2DEdit
        :visible="twoDimensionalVisible"
        :roomList="
        (currentTwoDimensional && currentTwoDimensional.room_list) || []
      "
        :editInfo="currentTwoDimensional && currentTwoDimensional.two_dimensional"
        :villageId="activeKey"
        :layerId="activeTwoDimensionalLayerId"
        :saveRequest="true"
        @handleClose="handleClose"
        @handleOK="handleOK"
    />
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  ref,
  toRefs,
  reactive,
  watch,
  nextTick,
  onUnmounted,
} from "vue";
import {
  QuestionCircleOutlined,
  CaretUpOutlined,
  EditOutlined,
  RedoOutlined,
} from "@ant-design/icons-vue";
import AddHouse from "./modules/AddHouse.vue";
import request from "../../../common/utils/request";
import { Empty, Modal } from "ant-design-vue";
import RoomDrawer from "../../../components/village/RoomDrawer.vue";
import store from "../../../store";
import moment from "moment";
import BLCOMMON from "bl-common-vue3";
import utils from "@/common/utils/utils";
import CanvasSelect from "canvas-select";
import Layer2DEdit from "@/views/village/BuildingManage/modules/Layer2DEdit.vue";
import _ from "lodash";
import { uuid } from "vue-uuid";

const SubMenu = {
  name: "SubMenu",
  props: {
    menuInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  template: `
    <a-sub-menu :key="menuInfo.id">
    <template #title>{{ menuInfo.title }}</template>
    <template v-for="item in menuInfo.children" :key="item.id">
      <template v-if="!item.children">
        <a-menu-item :key="item.id">
            <a-tooltip>
               <template #title>{{ item.title }}</template>
               <div class="textEllipsis">
                {{ item.title }}
               </div>
            </a-tooltip>
        </a-menu-item>
      </template>
      <template v-else>
        <sub-menu :menu-info="item" :key="item.id" />
      </template>
    </template>
    </a-sub-menu>
  `,
};

export default defineComponent({
  name: "PropertyManagement",
  components: {
    QuestionCircleOutlined,
    CaretUpOutlined,
    // ExpandOutlined,
    AddHouse,
    Empty,
    RoomDrawer,
    "sub-menu": SubMenu,
    CanvasSelect,
    Layer2DEdit,
    EditOutlined,
    RedoOutlined,
  },
  setup() {
    let state = reactive({
      viewMode: 1,
      checkedMode: true,
      showTwoDimensional: false, // 展示二维
      showTwoDimensLoading: false,
      twoDimensionalLayers: [],
      activeTwoDimensionalLayerId: 0,
      canvasInstance: null,
      twoDimensionalVisible: false,
    });
    const villageType = computed(() => store.getters.buildingInfo.villageType);
    const BgImg = utils.staticPath + "images/common/two_dimensional_bg.png";
    const currentTwoDimensional = computed(() =>
        state.twoDimensionalLayers.find(
            (v) => v.layer_id == state.activeTwoDimensionalLayerId
        )
    );

    watch(
        () => state.checkedMode,
        (val) => {
          if (val) {
            state.viewMode = 1;
          } else {
            state.viewMode = 2;
          }
        }
    );
    const getListStyle = (list) => {
      let style = {};
      if (state.viewMode == 2) {
        if (currentStatus.value != "") {
          let hide_all_item = true;

          list.map((item) => {
            if (
                currentStatus.value != "" &&
                item.roomColorType == colorType.value
            ) {
              hide_all_item = false;
            }
          });
          if (hide_all_item) {
            style.display = "none";
          }
        }
      }

      return style;
    };
    const activeKey = ref();
    const getItemStyle = (current) => {
      // console.log(current);
      let style = {
        width: current.area_proportion - 0.4 + "%",
        backgroundColor: current.roomColor,
      };
      if (current.show_status != 4) {
        style.border = "3px dashed #8fa3b7";
      }
      if (state.viewMode == 1) {
        if (
            currentStatus.value != "" &&
            colorType.value != current.roomColorType
        ) {
          style.opacity = 0.4;
        }
      } else {
        if (
            currentStatus.value != "" &&
            colorType.value != current.roomColorType
        ) {
          style.display = "none";
        }
      }

      return style;
    };

    // 搜索
    const value = ref("");
    const searchValue = ref("");
    const projectType = ref("");

    const onSearch = (value) => {
      profiles(value);
    };

    // 新增房源弹窗
    const visible = ref(false);

    const btnCancel = (type) => {
      visible.value = false;
      if (type == "success") {
        profiles(searchValue.value);
      }
    };

    const to3DView = () => {
      const { layerId, buildId, villageId } = view3dData.value;
      window.open(
          `${
              location.origin + location.pathname
          }#/main/3d/layer?layerId=${layerId}&buildId=${buildId}&villageId=${villageId}`
      );
    };

    const btnAdd = () => {
      visible.value = true;
    };

    // 剖面图切换
    // const switchValue = ref("a");

    const table = ref([]);
    const tabSpinning = ref(false);

    const offsetSectionHeight  = ref(0)
    // 剖面图数据列表
    const profileLsit = () => {
      request.get("/org", "/build/villageAndBuildList").then((res) => {
        const { checkedBuildings } = store.getters.buildingInfo;
        table.value = [];
        res.villageList.forEach((village) => {
          let checkedBuild = [];
          if (village.buildList && village.buildList.length) {
            village.buildList.forEach((build) => {
              if (checkedBuildings.includes(build.id)) {
                checkedBuild.push(build);
              }
            });
          }
          if (checkedBuild.length) {
            village.buildList = checkedBuild;
            let result = [];
            village.buildList.forEach((build) => {
              let regExp = new RegExp(
                  `(.+?(${BLCOMMON.utils.buildLevelArr.join("|")}))`
              );
              const match = regExp.exec(build.build_name);
              if (match) {
                const group1 = match[1]; // 提取"数字栋"
                if (
                    group1.length >= 2 &&
                    build.build_name.slice(group1.length).length > 0
                ) {
                  let index = result.findIndex((v) => v.title === group1);
                  if (index !== -1) {
                    result[index].children.push({
                      ...build,
                      title: build.build_name.slice(group1.length),
                      father: result[index].id,
                    });
                  } else {
                    result.push({
                      title: group1, // 2栋
                      id: `${village.arrKey}_buildLevel_${build.id}`,
                      childType: "buildLevel",
                      children: [
                        {
                          ...build,
                          title: build.build_name.slice(group1.length),
                          father: `${village.arrKey}_buildLevel_${build.id}`,
                        },
                      ],
                    });
                  }
                } else {
                  result.push({
                    ...build,
                    title: build.build_name,
                  });
                }
              } else {
                result.push({
                  ...build,
                  title: build.build_name,
                });
              }
            });
            result = result.map((v) => {
              if (v?.childType === "buildLevel" && v?.children?.length === 1) {
                v = { ...v.children[0] };
                v.title = v?.build_name;
                delete v.father;
              }
              return v;
            });
            village.buildLevelList = result;
            table.value.push(village);
          }
        });

        if (table.value.length) {
          activeKey.value = table.value[0].id;
          Tabchange(activeKey.value);
        }

        nextTick(()=>{
          let countDataHeightElement = document.getElementById('countDataRef')
          offsetSectionHeight.value = countDataHeightElement.offsetHeight + 15
        })
      });
    };
    profileLsit();
    const activeBuildId = ref([]);
    const openedMenu = ref([]);
    const getOpenKeyInfo = (list, id) => {
      let result = [];
      const getOpenKey = (data, targetId) => {
        data.forEach((v) => {
          if (v.id == targetId) {
            if (v?.father) {
              result = [v.father];
            }
          } else {
            if (v?.children?.length && !result.length) {
              getOpenKey(v.children, targetId);
            }
          }
        });
      };
      getOpenKey(list, id);
      return result;
    };

    const Tabchange = (value) => {
      const selectedItem = table.value.find((item) => item.id == value);
      activeBuildId.value =
          selectedItem.buildList && selectedItem.buildList.length
              ? [selectedItem.buildList[0].id]
              : [];
      openedMenu.value = [];
      if (selectedItem?.buildLevelList?.length) {
        let data = getOpenKeyInfo(
            selectedItem.buildLevelList,
            activeBuildId.value
        );
        if (data?.length) {
          openedMenu.value = data;
        }
      }
      for (let i = 0; i < table.value.length; i++) {
        if (table.value[i].id == value) {
          projectType.value = table.value[i].type;
        }
      }
      searchValue.value = "";
      currentStatus.value = "";
      colorType.value = "";
      if (state.canvasInstance) {
        state.canvasInstance.destroy();
        state.canvasInstance = null;
      }
      profiles();
    };

    const setCurrentRoomStyle = (info = {}, roomId, roomList = []) => {
      if (roomId) {
        let roomInfo = roomList.find((v) => v.id == roomId);
        info.bindRoomId = roomInfo.id;
        info.bindRoomInfo = roomInfo;
        let bindColor = roomInfo?.roomColor;
        if (bindColor) {
          let roomFillColor = utils.getHexOpacityColor({
            color: bindColor,
            opacity: 0.9,
          });
          info.strokeStyle = "#fff";
          info.roomLineColor = "#fff";
          info.fillStyle = roomFillColor;
          info.roomFillColor = roomFillColor;
        }
        info.label = roomInfo?.room_name || "";
        info.labelFont = "14px sans-serif";
      } else {
        info.label = "";
        info.strokeStyle = "#2681f3";
        info.fillStyle = "#fff";
        delete info.bindRoomId;
        delete info.bindRoomInfo;
        delete info.roomLineColor;
        delete info.roomFillColor;
      }
      return info;
    };


    /** 状态展示文字 */
    const getExpireTimeTxt = (room) => {
      //锁定房间
      if (room.is_lock) {
        // 如果是意向合同锁定
        if (room.extra_lock && room.extra_lock.length > 0) {
          room.lock_end_time = room.extra_lock[0].purposeUnlockTime;
          room.extra_lock.forEach((item) => {
            // 找出最近时间
            if (moment(item.purposeUnlockTime).isBefore(room.lock_end_time)) {
              room.lock_end_time = item.purposeUnlockTime;
            }
          });
          return `${room.lock_reason},锁定至${room.lock_end_time}`;
        } else {
          return `${room.lock_reason}`;
        }
      } else {
        const status = Number(room.show_status);
        if (status > 3 && status < 7) {
          return `${room.lease_end_date}到期`;
        } else if (status == 1) {
          return `空置${room.vacant_days}日`;
        } else if (status == 7) {
          return `${room.lease_end_date}已到期`;
        }
        return "";
      }
    };

    const profilesList = ref([]);
    const statusList = ref([]);

    const parseRatio = (number, decimal = 2) => {
      return (Math.floor(number * 100) / 100).toFixed(decimal);
    };

    // 设置空房间比例 endIndex不包含
    const setEmptyRoomRatio = (list, startIndex = 0, endIndex) => {
      endIndex = endIndex || list.length;
      let length = endIndex - startIndex;
      if (length < 10) {
        for (let i = startIndex; i < endIndex; i++) {
          list[i].areaRatio = parseRatio(100 / length);
        }
      } else {
        const remainder = length % 10;
        const integer = length / 10;
        for (let i = integer * 10; i < remainder; i++) {
          list[i].areaRatio = parseRatio(100 / remainder);
        }
      }
    };

    // 回溯处理
    const setBeforeArea = (list, lastIndex, currentIndex) => {
      if (currentIndex == 0) {
        list[0].areaRatio = 100;
        return;
      }
      const hasAreaRoom = [];
      let total = 0;
      for (let i = lastIndex; i < currentIndex; i++) {
        const item = list[i];
        if (Number(item.build_area)) {
          hasAreaRoom.push(item);
          total = Number(total) + Number(item.areaRatio);
        }
      }
      if (hasAreaRoom.length) {
        const emptyNum = currentIndex - lastIndex - hasAreaRoom.length;
        let remainTotal = 100 - emptyNum * 10; // 除去空房间剩余总空间
        for (let item of hasAreaRoom) {
          item.areaRatio = parseRatio(
              (Number(item.areaRatio) / total) * remainTotal
          );
        }
      } else {
        setEmptyRoomRatio(list, lastIndex, currentIndex);
      }
    };

    // 整理房间的最终比例
    const handleRoomFinalArea = (list) => {
      let total = 0;
      let lastIndex = 0;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        total = total + Number(item.areaRatio);
        if (i == list.length - 1) {
          if (total >= 100) {
            // 只剩最后一个会折行
            setBeforeArea(list, lastIndex, i);
            setBeforeArea(list, i, i + 1);
          } else {
            // 最后一行铺不满的情况
            setBeforeArea(list, lastIndex, i + 1);
          }
        } else if (total >= 100) {
          // 面积已满一行
          setBeforeArea(list, lastIndex, i);
          total = Number(item.areaRatio);
          lastIndex = i;
        }
      }
    };
    const profiles = (keywords) => {
      return new Promise((resolve) => {
        let params = {
          villageId: activeKey.value,
          buildId: activeBuildId.value[0],
          is_village : 1 ,
        };
        if (state.showTwoDimensional) {
          searchValue.value = "";
        }
        if (keywords && !state.showTwoDimensional) {
          params.keywords = keywords;
        }
        tabSpinning.value = true;
        request
            .get("/village", "/profile/profile", {
              ...params,
            })
            .then((res) => {
              // 处理房间数据
              if (res.list && res.list.length > 0) {
                res.list.forEach((layer) => {
                  let totalArea = Number(layer.build_area);
                  if (totalArea) {
                    //  有房间含有面积
                    const emptyRoom = layer.room_list.filter(
                        (item) => !item.build_area || item.build_area == 0
                    );
                    const emptyRoomArea = emptyRoom.length
                        ? totalArea * 10 * 0.01
                        : 0;
                    layer.room_list.forEach((room, roomIndex) => {
                      if (Number(room.build_area)) {
                        // 计算比例
                        room.areaRatio = parseRatio(
                            ((Number(room.build_area) + emptyRoomArea) /
                                totalArea) *
                            100
                        );
                        if (Number(room.areaRatio) > 100) {
                          room.areaRatio = 100;
                        }
                        if (Number(room.areaRatio) < 10) {
                          room.areaRatio = 10;
                        }
                      } else {
                        // 没有面积仍然算10%
                        room.areaRatio = 10;
                      }
                    });
                    handleRoomFinalArea(layer.room_list);
                  } else {
                    // 所有房间都是空的，超过10个房间按10%，不超过10个房间一行均分
                    setEmptyRoomRatio(layer.room_list);
                  }
                  if (layer.room_list && layer.room_list.length > 0) {
                    layer.room_list.forEach((room) => {
                      if (room.is_lock) {
                        room.locked_area = 0;
                        // 如果是意向合同锁定
                        if (room.extra_lock && room.extra_lock.length > 0) {
                          room.lock_end_time =
                              room.extra_lock[0].purposeUnlockTime;
                          room.extra_lock.forEach((item) => {
                            room.locked_area += item.leaseLockArea;
                            // 找出最近时间
                            if (
                                moment(item.purposeUnlockTime).isBefore(
                                    room.lock_end_time
                                )
                            ) {
                              room.lock_end_time = item.purposeUnlockTime;
                            }
                          });
                        } else {
                          // 手动锁定，锁定面积即为房间面积
                          room.locked_area = room.build_area;
                        }
                      }
                    });
                  }
                  if (layer?.two_dimensional?.coorList?.length) {
                    layer.two_dimensional.coorList.forEach((v) => {
                      if (v.bindRoomId) {
                        v = setCurrentRoomStyle(v, v.bindRoomId, layer.room_list);
                      }
                    });
                  } else {
                    // 初始化 (默认排列房间)
                    let editArr = [];
                    let percentTotal = 100;
                    let percentRow = 1;
                    let percentCol = 0;
                    let _roomList = (layer.room_list || []).map((v) => {
                      percentTotal = percentTotal - Number(v.areaRatio);
                      if (percentTotal < 0) {
                        percentTotal = 100;
                        percentRow++;
                        percentCol = 1;
                      } else {
                        percentCol++;
                      }
                      return {
                        id: v.id,
                        areaRatio: Number(v.areaRatio),
                        row: percentRow,
                        col: percentCol,
                      };
                    });
                    let gapWidth = 14;
                    let colHeight = 60;
                    for (let i = 0; i < _roomList.length; i++) {
                      let columnsTotal = _roomList.filter(
                          (item) => item.row == _roomList[i].row
                      );
                      let widthTotal =
                          1000 - (columnsTotal.length + 1) * gapWidth;
                      let colWidth = Number(
                          parseRatio((widthTotal * _roomList[i].areaRatio) / 100)
                      );
                      let beforeTotalArea = 0;
                      if (_roomList[i].col > 1) {
                        columnsTotal.forEach((item) => {
                          if (item.col < _roomList[i].col) {
                            beforeTotalArea =
                                Number(beforeTotalArea) +
                                Number(
                                    parseRatio((widthTotal * item.areaRatio) / 100)
                                );
                          }
                        });
                      }
                      let surplusHeight = 666;

                      if (_roomList[i].row > 1) {
                        surplusHeight =
                            666 -
                            (_roomList[i].row - 1) * colHeight -
                            (_roomList[i].row + 1) * gapWidth;
                      }
                      if (surplusHeight < colHeight) {
                        break;
                      }
                      _roomList[i].coor = [
                        [
                          gapWidth * _roomList[i].col + beforeTotalArea,
                          _roomList[i].row * gapWidth +
                          (_roomList[i].row - 1) * colHeight,
                        ],
                        [
                          gapWidth * _roomList[i].col +
                          beforeTotalArea +
                          colWidth,
                          gapWidth * _roomList[i].row +
                          _roomList[i].row * colHeight,
                        ],
                      ];
                      // console.log(beforeTotalArea,colWidth,widthTotal,_roomList[i].coor, 'beforeTotalArea====')
                      _roomList[i].index = i;
                      _roomList[i].type = 1;
                      _roomList[i].uuid = uuid.v4();
                      _roomList[i].creating = false;
                      _roomList[i].dragging = false;
                      _roomList[i].active = false;
                      setCurrentRoomStyle(
                          _roomList[i],
                          _roomList[i].id,
                          layer.room_list
                      );
                      editArr.push(_roomList[i]);
                    }
                    if (layer.two_dimensional?.bg_img) {
                      layer.two_dimensional.coorList = editArr
                    } else {
                      layer.two_dimensional = {
                        bg_img: '',
                        coorList: editArr,
                      }
                    }
                  }
                });
              }
              state.twoDimensionalLayers = res?.list || [];
              let findLayerId = state.twoDimensionalLayers.find(
                  (v) => v.layer_id == state.activeTwoDimensionalLayerId
              );
              state.activeTwoDimensionalLayerId = findLayerId
                  ? findLayerId.layer_id
                  : state.twoDimensionalLayers[0]?.layer_id;
              profilesList.value = res;
              statusList.value = res.room_status_color;
              tabSpinning.value = false;
              state.showTwoDimensLoading = false;
              if (state.showTwoDimensional) {
                let canvasWidth = document.getElementById(
                    `sectionDrawingCanvas${activeKey.value}`
                ).clientWidth;
                let height = canvasWidth * 0.666;
                document.getElementById(
                    `sectionDrawingCanvas${activeKey.value}`
                ).style.height = height + "px";
                nextTick(() => {
                  initCanvasInstance();
                });
              }
            });
      });
    };

    const view3dData = computed(() => {
      if (
          profilesList.value &&
          profilesList.value.list &&
          profilesList.value.list.length
      ) {
        for (let layer of profilesList.value.list) {
          if (layer.room_list && layer.room_list.length) {
            for (let room of layer.room_list) {
              if (room.three_dimensional_id) {
                return {
                  villageId: room.village_id,
                  buildId: room.build_id,
                  layerId: layer.layer_id,
                };
              }
            }
          }
        }
      }
      return {};
    });

    const visibleDetails = ref(false);

    const btnCancelDetails = () => {
      visibleDetails.value = false;
      profiles(searchValue.value);
    };

    const houseId = ref(0);
    const villageIdAdd = ref(0);
    const room_id = ref(0);
    const maxRoomNumber = ref(0);
    const roomDetail = ref({});
    const onRoomClick = (room, layer) => {
      roomDetail.value = room;
      maxRoomNumber.value = getMaxRoomNumber(layer.room_list);
      villageIdAdd.value = activeKey.value;
      visibleDetails.value = true;
    };
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    const buildMenuSelect = (value) => {
      currentStatus.value = "";
      colorType.value = "";
      searchValue.value = "";
      profiles();
    };

    // 招商中
    const currentStatus = ref("");
    const colorType = ref("");
    const handleStatusFilter = (value) => {
      if (state.showTwoDimensional) return;
      if (currentStatus.value == value.title) {
        currentStatus.value = "";
        return;
      }
      currentStatus.value = value.title;
      colorType.value = value.type + "_" + value.limit;
    };

    const to2DView = () => {
      state.showTwoDimensLoading = true;
      state.showTwoDimensional = !state.showTwoDimensional;
      if (state.showTwoDimensional) {
        profiles();
      } else {
        profiles();
        if (state.canvasInstance) {
          state.canvasInstance.destroy();
          state.canvasInstance = null;
        }
      }
    };

    const change2DLayer = (id) => {
      state.activeTwoDimensionalLayerId = id;
      initCanvasInstance();
    };

    const initCanvasInstance = () => {
      // 2D图初始化
      if (!state.canvasInstance) {
        state.canvasInstance = new CanvasSelect(
            `.canvas-sectionDrawing-${activeKey.value}`,
          currentTwoDimensional.value?.two_dimensional?.bg_img || BgImg
        );
        state.canvasInstance.fillStyle = "rgba(255, 255, 255)";
        state.canvasInstance.strokeStyle = "#2681f3";
        state.canvasInstance.activeFillStyle = "#d3e3fd";
        state.canvasInstance.activeStrokeStyle = "#2681f3";
        state.canvasInstance.on("select", (info) => {
          if (!info) return;
          info.active = false;
          // 点击有房间 展示房间详情 没有房间 提示或者设置房间
          if (info?.bindRoomId) {
            roomDetail.value = info.bindRoomInfo;
            maxRoomNumber.value = getMaxRoomNumber(
                currentTwoDimensional.value?.room_list || []
            );
            villageIdAdd.value = activeKey.value;
            visibleDetails.value = true;
          }
        });
      }
      state.canvasInstance.setImage(currentTwoDimensional.value?.two_dimensional?.bg_img || BgImg);
      state.canvasInstance.scrollZoom = false;
      let option = currentTwoDimensional.value?.two_dimensional?.coorList || [];
      // 加载数据
      // 加载数据
      state.canvasInstance.setData(option);
      state.canvasInstance.update();
    };

    const handleEditLayer = () => {
      // 编辑楼层2D 平面图
      state.twoDimensionalVisible = true;
    };

    const handleClose = () => {
      state.twoDimensionalVisible = false;
    };

    const handleOK = (val) => {
      profiles();
      handleClose();
    };

    const canvasFitZoom = () => {
      if (state.canvasInstance) {
        state.canvasInstance.fitZoom();
      }
    };

    onUnmounted(() => {
      if (state.canvasInstance) {
        state.canvasInstance.destroy();
        state.canvasInstance = null;
      }
    });

    return {
      ...toRefs(state),
      houseId,
      villageIdAdd,
      value,
      activeKey,
      activeBuildId,
      profilesList,
      currentStatus,
      statusList,
      visibleDetails,
      visible,
      room_id,
      table,
      view3dData,
      onSearch,
      searchValue,
      btnCancel,
      btnAdd,
      Tabchange,
      profiles,
      onRoomClick,
      roomDetail,
      btnCancelDetails,
      handleStatusFilter,
      getItemStyle,
      to3DView,
      tabSpinning,
      maxRoomNumber,
      getListStyle,
      villageType,
      openedMenu,
      buildMenuSelect,
      projectType,
      to2DView,
      change2DLayer,
      handleEditLayer,
      currentTwoDimensional,
      handleClose,
      handleOK,
      canvasFitZoom,

      offsetSectionHeight,
      getExpireTimeTxt
    };
  },
});
</script>

<style lang="less" scoped>
.top-tag {
  padding: 0px 16px;
  height: 28px;
  display: flex;
  align-items: center;
  border-radius: 40px;
  margin-right: 20px;
  border: 1px solid #f1f1f1;
  cursor: pointer;
  .icon {
    width: 14px;
    height: 14px;
  }
}
.top-tag-active {
  background: #f1f1f1;
}

i {
  font-style: normal;
}
:deep(.ant-tabs-bar) {
  margin: 0 !important;
}

.List {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
  max-width: 1300px;
  margin-left: 5px;
}

.room-left {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  background: #f7f7f7;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .layer-name {
    color: #000;
    font-weight: 600;
    font-size: 15px;
  }
}

.profile_map_item {
  min-height: 80px;
  margin-right: 5px;
  border-radius: 5px;
  margin-bottom: 3px;
  padding: 5px 8px;
  flex: 1;
  .Tag {
    float: right;
    top: 56px;
    left: 220px;
    font-size: 12px;
    margin-left: 4px;
    margin-top: -17px;
    height: 18px;
    color: #ffff;
    text-align: center;
    border-radius: 2px;
    padding: 0 4px;
  }
}

.profile_map_item :hover {
  cursor: pointer;
}

.profile_map_item1 {
  min-height: 80px;
  margin-right: 5px;
  border-radius: 5px;
  margin-bottom: 3px;
  padding: 5px 8px;
  //flex: 1;
  width: 200px !important;
  flex: none;

  .Tag {
    float: right;
    top: 56px;
    left: 220px;
    font-size: 12px;
    margin-left: 4px;
    margin-top: -17px;
    height: 18px;
    color: #ffff;
    text-align: center;
    border-radius: 2px;
    padding: 0 4px;
  }
}

.profile_map_item1 :hover {
  cursor: pointer;
}

.List :hover {
  z-index: 11;
  transform: scale(1.01);

  // filter: brightness(1.07);
}
.box :hover {
  transform: none;
}

.textEllipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ant-tabs-bar {
  margin-bottom: 0 !important;
}
.noData {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.build_level_menu {
  width: 100%;
  height: 100%;
  border-right: 1px solid #f0f0f0 !important;
}
.two_map_left {
  width: 72px;
  background-color: #9a9a9a;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  padding: 6px 0;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.active_map_left {
  background: @primary-color;
}

.canvas-container-wrap {
  width: 100%;
  position: relative;
  .canvas-sectionDrawing {
    width: 100%;
    height: 100%;
  }
  .canvas-container-action {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
:deep(.ant-tabs) {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs-content){
  width: 100%;
  height: 100%;
}
:deep(.ant-spin-nested-loading) {
  width: 100%;
  height: 100%;
}
:deep(.ant-spin-container) {
  width: 100%;
  height: 100%;
}
.section-box{
  width: 100%;
  .section-left{
    width: 140px;
    height: 100%;
    margin-right: 24px;
    overflow: hidden auto;
  }
  .section-right{
    flex: 1;
    height: 100%;
    overflow: hidden auto;
    .viewHide{
      display: none;
    }
    .room-right {
      display: flex;
      flex-wrap: wrap;
      margin-left: 6px;
      .room-box {
        padding: 3px 2px;
        min-width: 10%;
        position: relative;

        .room {
          height: 84px;
          padding: 4px 8px;
          border-radius: 6px;
          background: #a9dcfd;
          cursor: pointer;
          line-height: 20px;
          position: relative;
          &:hover {
            transform: scale(1.01);
            transition: all 0.2s;
            z-index: 100;
            box-shadow: @box-shadow-base;
          }
          .tenant-name {
            font-size: 12px;
            color: #000;
          }
          .expire-time {
            color: rgba(0, 0, 0, 0.35);
            font-size: 12px;
          }
          .room-bottom {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 12px;
            position: absolute;
            right: 4px;
            bottom: 4px;
            .room-tags {
              .tag {
                padding: 2px 4px;
                color: #fff;
                margin-right: 4px;
                border-radius: 2px;
              }
            }
          }
        }
        .bordered {
          border: 3px dashed rgb(143, 163, 183);
        }
        .dark {
          opacity: 0.4;
        }
      }
    }
  }
}

</style>
